<template>
  <div>
    <!--  <div>11:{{this.searchForm.tableCode}}</div> -->
    <SelfAdaption slot="adaption-bar">
      <Form :model="searchForm" ref="formSearch" slot="adaption-bar" class="ivu-form-no-margin-bottom" inline>
        <Form-item prop='code' label="编码：">
            <Input
                type="text"
                placeholder="请输入编码"
                v-model="searchForm.id"
            ></Input>
        </Form-item>
        <!-- 更换业务单元获取方式 -->
        <Form-item prop="locked" label="业务单元：" v-if="!useApiGetData && fromPage == 'creater'">
          <Select style="width: 100%" size="small" filterable clearable placeholder="请选择" v-model="searchForm.tableCode">
            <Option
              @click.native="changetableCode(item)"
              v-for="item in bussinessUnit"
              :value="item.vsiValue"
              :key="item.vsiValue"
              >{{ item.vsiValue }}</Option
            >
          </Select>
        </Form-item>
         <Form-item v-if="type !== 'rate' && !useApiGetData" prop="locked" label="二级组织：">
          <Select style="width: 100%" size="small" clearable placeholder="请选择" v-model="searchForm.company">
            <Option v-for="item in secondOrgan" :value="item.value" :key="item.value">{{ item.value }}</Option>
          </Select>
        </Form-item>

        <Form-item prop="locked" label="业务单元：" v-if="useApiGetData && fromPage == 'creater'">
          <Select style="width: 100%" filterable size="small" clearable placeholder="请选择" v-model="searchForm.tableCode">
            <Option
              @click.native="changetableCode(item)"
              v-for="item in bussinessUnit"
              :value="item.trgNode"
              :key="item.trgNode"
              >{{ item.trgNode }}</Option
            >
          </Select>
        </Form-item>
        <Form-item v-if="type !== 'rate' && useApiGetData" prop="locked" label="二级组织：">
          <Select style="width: 100%" size="small" clearable placeholder="请选择" v-model="searchForm.company">
            <Option v-for="item in secondOrgan" :value="item.nodeName" :key="item.nodeName">{{ item.nodeName }}</Option>
          </Select>
        </Form-item>
        <Form-item v-if="fromPage == 'creater'" :label="'状态：'">
          <Select v-model="searchForm.wfStatus" clearable>
            <Option v-for="item in processStatusList" :value="item.value" :key="item.value">{{
              item.text
            }}</Option>
          </Select>
        </Form-item>
        <!--  查询 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="searchValueSet" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="coverTable" :config="pageTableConfig" v-if="loadInit && showTable">
      <div slot="table-bar" v-if="fromPage == 'creater'">
          <RPButton optType="create" type="info" @click="showDownLoad" text="下载模板" />
        <uploadFile
          :code="searchForm.tableCode"
          :parentCode="this.vsCode"
          :url="uploadUrl"
          @uploadSuccess="uploadSuccess"
        ></uploadFile>
        <RPButton optType="create" type="info" text="导出" @click="batchExport" />
        <RPButton optType="create" type="info" text="删除" @click="batchDel"/>
        <RPButton optType="create" type="info" text="提交" @click="batchSubmit"/>
        <RPButton v-if="showAdd" optType="create" type="info" @click="add" />
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import { GetLists, columnList } from './columns.js'
import { GetCalLists, calColumnList } from './columnsCal.js'
import uploadFile from '../uploadFile/index.vue'
import CoverRateEdit from './CoverRateEdit.vue'
import CoverTargetEdit from './CoverTargetEdit.vue'
import coverApi from '@/api/cover.js'
import coverData from '@/api/data.js'
import revisionRecord from '../common/revisionRecord.vue'
import downLoadFile from '../common/downLoadFile.vue'
import { excludeHiddenBussinessUnit } from '@/tools/common.js'
import { approvalMix } from '@/views/todoCenter/myApproval/approval-mix'
import tableColumnSetting from '@/mixin/tableColumnSetting'
import { PROCESS_STATUS_LIST, PROCESS_STATUS_MAP } from '@/tools/common.js'
import coverDetail from './coverDetail.vue'
export default {
  name: 'cover',
  components: {
    uploadFile
  },
  mixins: [approvalMix, tableColumnSetting],
  props: {
    type: {
      type: String,
      default: 'rate'
    },
    title: {
      type: String,
      default: ''
    },
    tableTitle: {
      type: String,
      default: ''
    },
    pageTypeName: {
      type: String,
      default: ''
    },
    showAdd: {
      type: Boolean,
      default: true
    },
    uploadUrl: {
      type: String,
      default: 'rate'
    },
    downloadUrl: {
      type: String,
      default: 'rate'
    },
    vsCode: {
      type: String,
      default: ''
    },
    pageType: {
      type: String,
      default: ''
    },
    fromPage: {
      type: String,
      default: 'creater'
    },
    bussinessCode: {
       type: String,
      default: ''
    },
    '$route': {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      processStatusList: PROCESS_STATUS_LIST,
      loadInit: false,
      useApiGetData: true,
      //vsiDescription: '',
      //tableCode: 'SHARE_145_COUNT_TABLE_CODE',
      logTypeList: {
        creater: {
          rate: 8,
          target: 7,
          status: 6,
        },
        Summary: {
          rate: 4,
          target: 3,
          status: 2,
        }
      },
      select: '',
      searchForm: {
        id: '',
        tableCode: '',
        company: '',
        wfStatus: '',
        vsCode: this.vsCode,
        vsiDescription: '',
        fromPage: this.fromPage,
        self: this
      },
      bussinessUnit: [],
      secondOrgan: [],
      ids:[],
      pageTableConfig: {
        loadDataFn: this.type == 'rate' ? this.getwfRptDgCalList : this.type == 'target' ? this.getwfRptDgcalHrhxList : this.getCoverTargetList,
        columns: this.pageType == '3' ? GetCalLists.bind(this)() : GetLists.bind(this)(),
        autoFirst: false,
        onSelectionChange: this.onSelectionChange
      },
      // exportApi: {
      //   rate: coverApi.exportwfRptDgCal,
      //   target: coverApi.exportwfRptDgcalHrhx,
      //   status: coverApi.exportwfRptDgcalHrhxStatus,
      // }

       exportApi: {
        rate: this.url('itShare', '/wfRptDgCal/listExport'),
        target: this.url('itShare', '/wfRptDgcalHrhx/listExport'),
        status: this.url('itShare', '/wfRptDgcalHrhxStatus/listExport'),
      }
    }
  },
  computed: {
    menuNo() {
      let menuNo = ''
      // 2022年数字化覆盖现状
      if (this.type == 'status') {
        menuNo = this.fromPage == 'creater' ? 'status' : 'summary-status'
      // “十四五”数字化覆盖目标
      } else if (this.type == 'target') {
        menuNo = this.fromPage == 'creater' ? 'target' : 'summary-target'
      // 数字化覆盖率计算表
      } else if (this.type == 'rate') {
        menuNo = this.fromPage == 'creater' ? 'rate' : 'summary-rate'
      }
      return menuNo
    },
    columnList() {
      let list = ''
      // 2022年数字化覆盖现状
      if (this.type == 'status') {
        list = this.fromPage != 'creater' ? this.deleteField(columnList, 'wfStatusName') : columnList
      // “十四五”数字化覆盖目标
      } else if (this.type == 'target') {
        list = this.fromPage != 'creater' ? this.deleteField(columnList, 'wfStatusName') : columnList
      // 数字化覆盖率计算表
      } else if (this.type == 'rate') {
        list = this.fromPage != 'creater' ? this.deleteField(calColumnList, 'wfStatusName') : calColumnList
      }
      return list
    },
  },
  methods: {
    url(type, pathname) {
      return window.RPConfig[type] + pathname;
    },
    revisionRecord(row) {
      new this.$pageModal(
        revisionRecord,
        {
          props: {
            taskCode: row.taskCode,
            logType: this.logTypeList[this.fromPage][this.type]
          }
        },
      );
    },
    exportFun(row) {
      // 导出
      if(this.type == 'rate'){
        coverApi.downLoadFun({url: `${this.exportApi[this.type]}?id=${row.id}&trg_node&sed_type&first_type&task_code`})

      }else{
         coverApi.downLoadFun({url: `${this.exportApi[this.type]}?id=${row.id}&trg_node&dpt&company&task_code`})
      }
    },
    deleteFun(params) {
      let ids = []
      if (Array.isArray(params)) {
        ids = [...params]
      } else if (params.id) {
        ids.push(params.id)
      }
       this.$confirm({
          title:"删除",
          content: "当前表删除后不可撤回，您是否要继续删除?"
        }).then(()=>{
          if(this.type == 'rate') {
            coverApi.deletewfRptDgCal(
              {
                type: this.fromPage,
                data: ids
              }
            ).then((result) => {
              if(result.data.code == 200){
                this.$Message.success({
                  content: '删除成功',
                  duration: 3
              })
            } else {
              this.$Message.error({
                content: result.data.msg || '删除失败',
                duration: 3
                })
              }
              this.searchValueSet()
            })
          } else if (this.type == 'target') {
            coverApi.deletewfRptDgcalHrhx({
              type: this.fromPage,
              data: ids
            }).then((result) => {
              if(result.data.code == 200){
                this.$Message.success({
                  content: '删除成功',
                  duration: 3
              })
            } else {
              this.$Message.error({
                content: result.data.msg || '删除失败',
                duration: 3
                })
              }
              this.searchValueSet()
            })
          } else {
            coverApi.coverDelete({
              type: this.fromPage,
              data: ids
            }).then((result) => {
              if(result.data.code == 200){
                this.$Message.success({
                  content: '删除成功',
                  duration: 3
              })
            } else {
              this.$Message.error({
                content: result.data.msg || '删除失败',
                duration: 3
                })
              }
            this.searchValueSet()
          })
          }

        })

      //删除
    },
    //获取业务单元
    init() {
      if (this.useApiGetData) {
           // 更换业务单元获取方式
        coverApi.getRptReportTrgnodePList({reportName: "关键业务环节数字化覆盖度"}).then(res => {
            this.bussinessUnit = res.data.data
            this.bussinessUnit = excludeHiddenBussinessUnit(this.bussinessUnit)
            this.select = this.bussinessUnit[0]
            if (this.fromPage != 'creater') {
              this.searchForm.tableCode = this.bussinessCode
              let selectData = this.bussinessUnit.find(item => item.trgNode == this.searchForm.tableCode)
              if (selectData) {
                coverApi.getRptTrgnodeTree({parentNodeCode: selectData.nodeId}).then(second => {
                  this.secondOrgan = second.data.data
                })
              }
            }
            // this.searchForm.tableCode = this.bussinessUnit[0].nodeName
            this.loadInit = true
            this.$nextTick(() => {
              this.searchValueSet()
            })

          })
      } else {
          var newData = coverData.data.filter(function (res) {
            return res.value !== '华润医药集团有限公司'
          })
          this.bussinessUnit = newData
          if (this.fromPage != 'creater') {
            this.searchForm.tableCode = this.bussinessCode
            let selectData = this.bussinessUnit.find(item => item.vsiValue == this.searchForm.tableCode)
            this.secondOrgan = selectData ? selectData.children : []
          }

          this.select = this.bussinessUnit[0]
          this.loadInit = true

           this.$nextTick(() => {
              this.searchValueSet()
            })
      }

    },
    //二级组织
    changetableCode(item) {
      if (this.useApiGetData) {
       coverApi.getRptTrgnodeTree({parentNodeCode: item.nodeId}).then(second => {
          this.secondOrgan = second.data.data
        })
      } else {
      // 更换业务单元获取方式
        this.secondOrgan = item.children
        this.searchForm.company = ''
      }

    },

    //获取覆盖率列表
    getwfRptDgCalList: tableObj => {
      let { responseProcess, param } = tableObj
      let { pageNum, pageSize, id, tableCode, wfStatus, self} = param
      let paramsData = {
        taskCode: id,//:"编码",
        trgNode: tableCode,// "业务单元",
        wfStatus: wfStatus,
        currentPage: pageNum, //-----当前页码
        pageSize: pageSize //-----每页条数
        // sortOrderBy: 'DESC',
        // sortPropName: 'create_time'
      }
      return coverApi.getwfRptDgCalList({
        data: paramsData,
        type: param.fromPage
      }).then(res => {
        if(res.data.code == 200) {
          let data = res.data
          let { current, records, size, total } = data.data
          if(records && records.length) {
            records.forEach(element => {
              element.wfStatusName = PROCESS_STATUS_MAP[element.wfStatus]
            });
          }
          responseProcess({
            pageNum: Number(current),
            pageSize: Number(size),
            records: records || [],
            total: Number(total)
          })
        } else {
          self.$Message.error({
            content: res.data.msg || '操作失败',
            duration: 3
          })
        }
        self.ids = []
      })
    },
    //获取覆盖目标、状态列表
    getCoverTargetList: tableObj => {
      let { responseProcess, param } = tableObj
      let { pageNum, pageSize, id, company, tableCode, wfStatus, self } = param
      let paramsData = {
        taskCode: id,//:"编码",
        trgNode: tableCode,// "业务单元",
        company: company,//"二级组织",
        wfStatus: wfStatus,
        currentPage: pageNum, //-----当前页码
        pageSize: pageSize //-----每页条数
        // sortOrderBy: 'DESC',
        // sortPropName: 'create_time'
      }
      return coverApi.getCoverTargetList({
        data: paramsData,
        type: param.fromPage
      }).then(res => {
        if(res.data.code == 200) {
          let data = res.data
          let { current, records, size, total } = data.data
          if(records && records.length) {
            let statusMap = {
              '1': '待提交',
              '2': '待审核',
              '3': '审核通过',
              '4': '驳回',
            }
            records.forEach(element => {
              element.wfStatusName = statusMap[element.wfStatus]
            });
          }
          responseProcess({
            pageNum: Number(current),
            pageSize: Number(size),
            records: records || [],
            total: Number(total)
          })
        } else {
            self.$Message.error({
              content: res.data.msg || '操作失败',
              duration: 3
            })
          }
          self.ids = []
      })
    },
     //获取覆盖目标、状态列表
    getwfRptDgcalHrhxList: tableObj => {
      let { responseProcess, param } = tableObj
      let { pageNum, pageSize, id, company, tableCode, wfStatus, self } = param
      let paramsData = {
        taskCode: id,//:"编码",
        trgNode: tableCode,// "业务单元",
        wfStatus: wfStatus,
        company: company,//"二级组织",
        currentPage: pageNum, //-----当前页码
        pageSize: pageSize //-----每页条数
        // sortOrderBy: 'DESC',
        // sortPropName: 'create_time'
      }
      return coverApi.getwfRptDgcalHrhxList({
        data: paramsData,
        type: param.fromPage
      }).then(res => {
        if(res.data.code == 200) {
          let data = res.data
          let { current, records, size, total } = data.data
          if(records && records.length) {
            let statusMap = {
              '1': '待提交',
              '2': '待审核',
              '3': '审核通过',
              '4': '驳回',
            }
            records.forEach(element => {
              element.wfStatusName = statusMap[element.wfStatus]
            });
          }
          responseProcess({
            pageNum: Number(current),
            pageSize: Number(size),
            records: records || [],
            total: Number(total)
          })
        } else {
            self.$Message.error({
              content: res.data.msg || '操作失败',
              duration: 3
            })
          }
          self.ids = []
      })
    },
    goDetail(row) {
        //  new this.$sidelipPage(
        //   coverDetail,
        //   {
        //     props: {
        //       title: row.trgNode + this.pageTypeName + '_'+ this.tableTitle + (row.year || ''),
        //       id: row.id,
        //       disabledPage: true,
        //       vsCode: this.vsCode,
        //       Code: this.searchForm.tableCode,
        //       dataStatus: Number(row.wfStatus) || 3,
        //       fromPage: this.fromPage
        //     }
        //   },
        //   data => {
        //     data && this.searchValueSet()
        //   }
        // )
      // 跳转详情
      if (this.type == 'rate') {
       new this.$sidelipPage(
          CoverRateEdit,
          {
            props: {
              title: this.title + '详情',
              id: row.id,
              disabledPage: true,
              vsCode: this.vsCode,
              Code: this.searchForm.tableCode,
              dataStatus: Number(row.wfStatus) || 3,
              fromPage: this.fromPage
            }
          },
          data => {
            data && this.searchValueSet()
          }
        )
      } else {
        if (this.type == 'status') {
          new this.$sidelipPage(
            coverDetail,
            {
              props: {
                title: row.trgNode + this.pageTypeName + '_'+ this.tableTitle + (row.year || ''),
                id: row.id,
                disabledPage: true,
                vsCode: this.vsCode,
                Code: this.searchForm.tableCode,
                dataStatus: Number(row.wfStatus) || 3,
                fromPage: this.fromPage
              }
            },
            data => {
              data && this.searchValueSet()
            }
          )
        } else {
          new this.$sidelipPage(CoverTargetEdit, {
            props: {
              title: this.title + '详情',
              id: row.id,
              disabledPage: true,
              type: this.type,
              vsCode: this.vsCode,
              Code: this.searchForm.tableCode,
              dataStatus: Number(row.wfStatus) || 3,
              fromPage: this.fromPage
            }
          })
        }
      }
    },
    goEdit(row) {
      // 跳转新增页面
      if (this.type == 'rate') {
        new this.$sidelipPage(
          CoverRateEdit,
          {
            props: {
              title: this.title + '编辑',
              id: row.id,
              vsCode: this.vsCode,
              Code: this.searchForm.tableCode,
              dataStatus: Number(row.wfStatus) || 3,
              fromPage: this.fromPage
            }
          },
          data => {
             let { pageNum } = this.$refs['coverTable'].param
            data && this.searchValueSet(pageNum)
          }
        )
      } else {
        new this.$sidelipPage(
          CoverTargetEdit,
          {
            props: {
              title: this.title + '编辑',
              id: row.id,
              type: this.type,
              vsCode: this.vsCode,
              Code: this.searchForm.tableCode,
              dataStatus: Number(row.wfStatus) || 3,
              fromPage: this.fromPage
            }
          },
          data => {
            let { pageNum } = this.$refs['coverTable'].param
            data && this.searchValueSet(pageNum)
          }
        )
      }
    },
    // 导入成功回调
    uploadSuccess() {
      this.searchValueSet()
    },
    showDownLoad() {
      if (this.type == 'rate') {
        this.downloadTemplate()
      } else {
        if (this.bussinessUnit && this.bussinessUnit.length) {
          new this.$pageModal(
            downLoadFile,
            {
              props: {
                bussinessUnit: this.bussinessUnit,
              }
            },
            (data) => {
              data && this.downloadTemplate(data)
            }
          );
        } else {
          this.$Message.error({
            content: '暂无业务单元数据',
            duration: 3
          })
        }
      }


    },
    downloadTemplate(trgNode = null) {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = trgNode ? `${this.downloadUrl}?TrgNode=${trgNode}` : this.downloadUrl
      link.setAttribute('download', 'fillname')
      document.body.appendChild(link)
      link.click()
      link.remove()
        //模板下载
    },
    //搜索
    searchValueSet(pageNum = null) {
      // this.select = this.bussinessUnit.find(item => item.vsiValue == this.searchForm.tableCode).value
      this.$refs['coverTable'].load(this.searchForm, pageNum)
    },
    add() {
      // 跳转新增页面
      if (this.type == 'rate') {
        new this.$sidelipPage(
          CoverRateEdit,
          {
            props: {
              title: this.title + '新建',
              vsCode: this.vsCode,
              Code: ''
            }
          },
          data => {
            data && this.searchValueSet()
          }
        )
      } else {
        new this.$sidelipPage(
          CoverTargetEdit,
          {
            props: {
              title: this.title + '新建',
              type: this.type,
              vsCode: this.vsCode,
              Code: ''
            }
          },
          data => {
            data && this.searchValueSet()
          }
        )
      }
    },
    // 批量提交
    commitFun(ids, api) {
      this.$confirm({
        title:"提交",
        content: "是否要批量提交?"
      }).then(()=>{
        api(
          {
            data: ids
          }
        ).then((result) => {
            if(result.data.code == 200){
              this.$Message.success({
                content: '提交成功',
                duration: 3
            })
          } else {
              this.$Message.error({
                content: result.data.msg || '提交失败',
                duration: 3
            })
          }
          this.searchValueSet()
        })
      })
    },
    // 批量导出
    listExport(ids) {
      this.$confirm({
        title:"导出",
        content: "是否要批量导出?"
      }).then(()=>{
        if(this.type === 'status') {
          const url = window.origin + '/' +this.getUrl('itShare', `/wfRptDgcalHrhxStatus/listExport`)
          coverApi.downloadFile2(url, ids)
        }
        if(this.type === 'target') {
          const url = window.origin + '/' +this.getUrl('itShare', `/wfRptDgcalHrhx/listExport`)
          coverApi.downloadFile2(url, ids)
        }
        if(this.type === 'rate') {
          const url = window.origin + '/' +this.getUrl('itShare', `/wfRptDgCal/listExport`)
          coverApi.downloadFile2(url, ids)
        }
      })
    },
    onSelectionChange(selection) {
        this.ids = []
         selection.forEach(element => {
          this.ids.push({id: element.id, wfStatus: element.wfStatus, trgNode: element.trgNode})
         });
    },
    getUrl(type, pathname) {
      return window.RPConfig[type] + pathname;
    },
    // 批量导出
    batchExport () {
      if(this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      if(this.type == 'rate') {
        this.ids.forEach(item => {
          // 状态为2(待审核)时无法导出
          if(!this.ids.some(e => e.wfStatus == 2)) {
            ids.push(item.id)
          }
        })
        if(ids.length > 0) {
          this.listExport(ids)
        } else {
          this.$Message.error({
            content: '状态为待审核的数据不可导出，请重试',
            duration: 3
          })
        }
      } else {
        this.ids.forEach(item => {
          // 状态为2(待审核)且业务单元不同时无法导出
          if(!this.ids.some(e => e.wfStatus == 2) && this.ids.findIndex((e) => e.trgNode == item.trgNode) == 0) {
              ids.push(item.id)
          }
        })
        if(ids.length > 0 && ids.length == this.ids.length) {
          this.listExport(ids)
        } else {
          this.$Message.error({
            content: '同一业务单元且状态不为待审核的数据可批量导出，请重试',
            duration: 3
          })
        }
      }
    },
    // 批量删除
    batchDel () {
      if(this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      this.ids.forEach(item => {
        // 状态为1(待提交)时可以删除
        if(item.wfStatus == 1 && this.ids.filter(e => e.wfStatus == 1).length === this.ids.length) {
          ids.push(item.id)
        }
      })
      if(ids.length > 0) {
        this.deleteFun(ids)
      } else {
        this.$Message.error({
          content: '仅状态为待提交的数据可以删除，请重试',
          duration: 3
        })
      }
    },
    // 批量提交
    batchSubmit() {
      if(this.ids.length === 0) {
        this.$Message.error({
          content: '请选择数据后再进行操作',
          duration: 3
        })
        return
      }
      const ids = []
      this.ids.forEach(item => {
        // 状态为1提交
        if(item.wfStatus == 1 && this.ids.filter(e => e.wfStatus == 1).length === this.ids.length) {
          ids.push(item.id)
        }
      })
      if(ids.length > 0) {
        if(this.type == 'status') {
          this.commitFun(ids, coverApi.statusCommit)
        } else if(this.type == 'target') {
          this.commitFun(ids, coverApi.targetCommit)
        } else if(this.type == 'rate') {
          this.commitFun(ids, coverApi.rateCommit)
        }
      } else {
        this.$Message.error({
          content: '仅状态为待提交的数据可以提交，请重试',
          duration: 3
        })
      }
    },
  },
  created() {
    // this.getLevelList()
  },
  // mounted() {
  //   this.getData()
  // }
}
</script>

<style lang="less" scoped>
/deep/.table-bar button:last-child {
  color: #ffffff;
  background-color: #ff6f4b;
  border-color: #ff6f4b;
}
</style>
